from django.shortcuts import render
from django.http import JsonResponse
from django_redis import get_redis_connection
from django.views import View
from django.contrib.auth import login, logout, authenticate
from django.conf import settings

import json
import re
from apps.users.models import User
import logging
from ihome_team7.libs.qiniuyun.qiniuyun_upload import storage
from ihome_team7.utils.decorator import LoginRequiredJSONMixin

logger = logging.getLogger('django')


# Create your views here.


class Register(View):
    """用户注册"""

    def post(self, request):
        """
        注册逻辑
        :param request: 手机 短信验证码 密码
        :return:
        """

        # 1.获取参数
        data = json.loads(request.body)
        mobile = data.get('mobile')
        phonecode = data.get('phonecode')
        password = data.get('password')

        # 2.校验参数
        if not all([mobile, phonecode, password]):
            return JsonResponse({'errno': 4103, 'errmsg': '缺少必传参数'})

        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse({'errno': 4103, 'errmsg': 'mobile参数错误'})

        if not re.match(r'^[0-9A-Za-z]{8,20}$', password):
            return JsonResponse({'errno': 4103, 'errmsg': 'password参数错误'})

        # 获取短信验证码
        conn = get_redis_connection('verify_code')
        sms_code = conn.get('sms_%s' % mobile)

        if not sms_code:
            return JsonResponse({'errno': 4002, 'errmsg': '短信验证码过期'})

        if sms_code.decode() != phonecode:
            return JsonResponse({'errno': 4103, 'errmsg': '短信验证码错误'})

        # 3.数据处理
        try:
            user = User.objects.create_user(username=mobile, mobile=mobile, password=password)
        except Exception as e:
            logger.error(e)
            return JsonResponse({'errno': 4001, 'errmsg': '创建用户失败'})

        # 保持登录状态
        login(request, user)

        # 4.返回响应对象
        response = JsonResponse({"errno": "0", "errmsg": "注册成功"})
        response.set_cookie('username', user.username, max_age=3600 * 24 * 14)
        return response


class Login(View):
    """用户登录"""

    def post(self, request):
        """
        登录逻辑
        :param request: 手机号 密码
        :return:
        """

        # 1.提取参数
        data = json.loads(request.body)
        mobile = data.get('mobile')
        password = data.get('password')

        # 2.校验参数
        if not all([mobile, password]):
            return JsonResponse({'errno': 4103, 'errmsg': '缺少必传参数'})

        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse({'errno': 4103, 'errmsg': 'mobile参数错误'})

        if not re.match(r'^[0-9A-Za-z]{8,20}$', password):
            return JsonResponse({'errno': 4103, 'errmsg': 'password参数错误'})

        # 认证用户登录
        user = authenticate(username=mobile, password=password)

        if not user:
            return JsonResponse({'errno': 4104, 'errmsg': '用户名或密码错误'})

        login(request, user)

        # 3.返回响应结果
        response = JsonResponse({"errno": "0", "errmsg": "注册成功"})
        response.set_cookie('username', user.username, max_age=3600 * 24 * 14)
        return response

    def get(self, request):
        """
        用户是否登录逻辑
        :param request:  无
        :return:  {"errno": "0","errmsg": "已登录","data": {"name": "用户名"}}
        """
        # 1.获取user对象
        user = request.user

        # 2.构建返回数据
        data = {
            "user_id": user.id,
            'name': user.username
        }

        # 3.判断用户是否登录
        if user.is_authenticated:
            return JsonResponse({'errno': '0', 'errmsg': '已登录', 'data': data})
        else:
            return JsonResponse({"errno": "4101", "errmsg": "未登录"})

    def delete(self, request):
        """
        用户退出
        :param request: 无
        :return:
        """

        # 1.清除session
        logout(request)

        # 2.构建响应对象
        response = JsonResponse({"errno": "0", "errmsg": "已登出"})

        # 3.清除cookie
        response.delete_cookie('username')
        return response


class UserCenter(LoginRequiredJSONMixin, View):
    """用户中心"""

    def get(self, request):
        """展示用户中心"""

        # 1.提取参数
        user = request.user
        avatar = user.avatar
        create_time = user.date_joined
        mobile = user.mobile
        name = user.username
        user_id = user.id

        # 2.返回响应结果
        return JsonResponse({
            "data": {
                "avatar_url": str(avatar),
                "create_time": create_time,
                "mobile": mobile,
                "name": name,
                "user_id": user_id
            },
            "errmsg": "OK",
            "errno": "0"
        })


class UserAvatar(View):
    """用户头像"""

    def post(self, request):
        """
        上传头像
        :param request:
        :return:
        """

        # 1.提取参数
        file = request.FILES.get('avatar')
        data = file.read()
        avatar_url = storage(data)
        real_url = settings.QNY_HOST + avatar_url
        user = request.user
        user.avatar = real_url
        user.save()

        # 2.返回响应对象
        return JsonResponse({
            "data": {
                "avatar_url": real_url
            },
            "errno": "0",
            "errmsg": "头像上传成功"
        })


class ChangeUsername(View):
    """修改用户名"""

    def put(self, request):
        # 1.提取参数
        data = json.loads(request.body)
        new_name = data.get('name')
        user = request.user
        user.username = new_name
        user.save()

        # 2.返回响应结果
        return JsonResponse({
            "errno": "0",
            "errmsg": "修改成功"
        })


class UserAuth(View):
    """实名认证"""

    def post(self, request):
        """

        :param request:  real_name id_card
        :return:
        """

        # 1.提取参数
        data = json.loads(request.body)
        real_name = data.get('real_name')
        id_card = data.get('id_card')

        # 2.校验参数
        if not all([real_name, id_card]):
            return JsonResponse({'errno': 4103, 'errmsg': '缺少必传参数'})

        if not re.match('^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$', id_card):
            return JsonResponse({'errno': 4103, 'errmsg': 'id_card参数错误'})

        # 3.处理数据
        user = request.user
        user.id_card = id_card
        user.real_name = real_name
        user.save()

        # 4.返回响应结果
        return JsonResponse({
            "errno": "0",
            "errmsg": "认证信息保存成功"
        })
